import React, { useState, useEffect } from 'react';
import { Layout, Menu, Button, Space, Dropdown, message, Avatar } from 'antd';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { 
  UserOutlined, 
  LoginOutlined, 
  LogoutOutlined,
  ShoppingCartOutlined,
  HeartOutlined,
  MobileOutlined,
  DownOutlined,
  EnvironmentOutlined
} from '@ant-design/icons';
import { authService } from '../services/api';
import '../styles/AppHeader.css';

const { Header } = Layout;

const AppHeader = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userInfo, setUserInfo] = useState(null);
  const [currentCity, setCurrentCity] = useState('宁波');

  // 检查登录状态和获取用户信息
  useEffect(() => {
    const token = localStorage.getItem('token');
    // 兼容后端返回结构
    let storedUserInfo = authService.getUserInfo();
    if (!storedUserInfo) {
      // 兼容直接用localStorage.getItem('userInfo')
      try {
        storedUserInfo = JSON.parse(localStorage.getItem('userInfo'));
      } catch (e) {}
    }
    if (token || storedUserInfo) {
      setIsLoggedIn(true);
      if (storedUserInfo) {
        setUserInfo(storedUserInfo);
        // 如果有用户信息但没有token，生成一个模拟token并保存
        if (!token) {
          localStorage.setItem('token', 'mock-auth-token-' + Date.now());
        }
      } else {
        // 如果本地没有用户信息但有token，尝试从服务器获取
        authService.getCurrentUser()
          .then(response => {
            const userData = response.data;
            setUserInfo(userData);
            authService.saveUserInfo(userData);
          })
          .catch(error => {
            console.error('Failed to get user info:', error);
            if (error.response && error.response.status === 401) {
              handleLogout();
            }
          });
      }
    } else {
      setIsLoggedIn(false);
      setUserInfo(null);
    }
  }, [location.pathname]);

  const handleLogout = () => {
    authService.logout();
    setIsLoggedIn(false);
    setUserInfo(null);
    message.success('已成功退出登录');
    navigate('/');
  };

  const handleMenuClick = (key) => {
    switch (key) {
      case 'profile':
        navigate('/profile');
        break;
      case 'orders':
        navigate('/orders');
        break;
      case 'logout':
        handleLogout();
        break;
      default:
        break;
    }
  };

  const userMenuItems = [
    {
      key: 'profile',
      label: '个人中心',
      icon: <UserOutlined />,
      onClick: () => handleMenuClick('profile')
    },
    {
      key: 'orders',
      label: '我的订单',
      icon: <ShoppingCartOutlined />,
      onClick: () => handleMenuClick('orders')
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: () => handleMenuClick('logout')
    }
  ];

  const menuItems = [
    {
      key: '/',
      label: <Link to="/">首页</Link>
    },
    {
      key: '/movies',
      label: <Link to="/movies">影片</Link>
    },
    {
      key: '/cinemas',
      label: <Link to="/cinemas">影院</Link>
    }
  ];

  return (
    <div className="header-container">
      {/* 顶部导航 */}
      <div className="top-header">
        <div className="top-header-content">
          <div className="left-section">
            <Link to="/" className="welcome-text">欢迎来到淘票票</Link>
            {!isLoggedIn ? (
              <Space>
                <Link to="/login">请登录</Link>
                <Link to="/register">免费注册</Link>
              </Space>
            ) : (
              <Dropdown menu={{ items: userMenuItems }} placement="bottomRight">
                <span className="user-dropdown" style={{ cursor: 'pointer' }}>
                  {userInfo?.avatar ? (
                    <Avatar src={userInfo.avatar} size="small" style={{ marginRight: 8 }} />
                  ) : (
                    <UserOutlined style={{ marginRight: 8 }} />
                  )}
                  {/* 优先显示nickname，其次username，其次userId */}
                  {userInfo?.nickname || userInfo?.username || userInfo?.userId || '用户'} <DownOutlined />
                </span>
              </Dropdown>
            )}
          </div>
          <div className="right-section">
            <Space split="|">
              <Link to="/help">帮助中心</Link>
              <Link to="/mobile">
                <MobileOutlined /> 手机购票
              </Link>
              <Link to="/cart">
                <ShoppingCartOutlined /> 购物车
              </Link>
              <Link to="/favorites">
                <HeartOutlined /> 收藏夹
              </Link>
            </Space>
          </div>
        </div>
      </div>

      {/* 主导航 */}
      <Header className="main-header">
        <div className="main-header-content">
          <div className="logo">
            <Link to="/">
              <span className="logo-text">淘票票</span>
            </Link>
          </div>
          <div className="city-selector">
            <EnvironmentOutlined />
            <span>{currentCity}</span>
            <DownOutlined />
          </div>
          <Menu 
            mode="horizontal" 
            selectedKeys={[location.pathname]}
            className="main-menu"
            items={menuItems}
          />
          <div className="mobile-download">
            <MobileOutlined /> 手机购票
          </div>
        </div>
      </Header>
    </div>
  );
};

export default AppHeader; 